package com.loren.demo25.filter;

import com.loren.demo25.utils.LogMdcUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter(filterName = "logFilter", urlPatterns = "/*")
public class LogFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        if (!(servletRequest instanceof HttpServletRequest)) {
            chain.doFilter(servletRequest, servletResponse);
            return;
        }
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String requestId = request.getHeader(LogMdcUtils.REQUEST_ID);
        if (StringUtils.isBlank(requestId)) {
            requestId = LogMdcUtils.getRequestId();
        }
        MDC.put(LogMdcUtils.REQUEST_ID, requestId);
        try {
            chain.doFilter(request, servletResponse);
        } finally {
            MDC.remove(LogMdcUtils.REQUEST_ID);
        }
    }
}